#ifndef _PROCESS_POOL_HPP
#define _PROCESS_POOL_HPP

#include <iostream>
#include <vector>
#include <cstdio>
#include <unistd.h>
#include <string>
#include <sys/wait.h>
#include "myTask.hpp"

class Channel
{
public:
    Channel(int fd, pid_t subid) : _fd(fd), _subid(subid)
    {
        _name = "channel-" + std::to_string(fd) + '-' + std::to_string(subid);
    }
    int Fd() { return _fd; }
    pid_t Subid() { return _subid; }
    std::string Name() { return _name; }
    void Send(int task_code)
    {
        int n = write(_fd, &task_code, sizeof(task_code));
        (void)n;
    }
    void Close()
    {
        close(_fd);
    }
    void Wait()
    {
        pid_t rid = waitpid(_subid, nullptr, 0);
        (void)rid;
    }
    ~Channel() {}

private:
    int _fd;
    pid_t _subid;
    std::string _name;
};

class ChannelManager
{
public:
    ChannelManager() {};
    ~ChannelManager() {};

    // 轮询
    Channel &Select()
    {
        auto &c = _channels[_next];
        _next++;
        _next %= _channels.size();
        return c;
    }
    void Insert(int wfd, int subid)
    {
        _channels.emplace_back(wfd, subid);
    }
    void PrintChannel()
    {
        for (auto &channel : _channels)
        {
            std::cout << channel.Name() << '\n';
        }
    }
    void StopSubProcess()
    {
        for(auto& channel:_channels)
        {
            channel.Close();
            std::cout << "关闭：" << channel.Name() << '\n';
        }
    }
    void WaitSubProcess()
    {
        for(auto& channel:_channels)
        {
            std::cout << "回收子进程：" << channel.Name() << '\n';
            channel.Wait();
        }
    }
private:
    std::vector<Channel> _channels;
    int _next;
};

const int process_num = 5;
class ProcessPool
{
public:
    ProcessPool(int num) : _process_num(num) 
    {
        _tm.Register(PrintLog);
        _tm.Register(DownLoad);
    }
    void Work(int rfd)
    {
        while (true)
        {
            int code = 0;
            ssize_t n = read(rfd, &code, sizeof(code));
            if(n > 0)
            {
                if(n != sizeof(code))
                {
                    continue;
                }
                std::cout << "子进程[" << getpid() <<"]" << "子进程收到任务码：" << code << '\n';
                _tm.Execute(code);
            }
            else if(n == 0)
            {
                std::cout << "子进程退出"  << '\n';
                break;
            }
            else
            {
                std::cout << "读取错误" << '\n';
                break;
            }
        }
    }
    bool Create()
    {
        for (int i = 0; i < _process_num; i++)
        {
            int pipefd[2] = {0};
            int n = pipe(pipefd);
            if (n < 0)
                return false;

            pid_t subid = fork();
            if (subid == 0)
            {
                close(pipefd[1]);
                Work(pipefd[0]);
                close(pipefd[0]);
                exit(0);
            }
            else if (subid > 0)
            {
                close(pipefd[0]);
                _cm.Insert(pipefd[1], subid);
                // close(pipefd[1]);
            }
            else
                exit(0);
        }
        return true;
    }
    void Debug()
    {
        _cm.PrintChannel();
    }
    // void PushTask(int task_code)
    // {
    //     auto &c = _cm.Select();
    //     std::cout << "选择一个子进程：" << c.Name() << '\n';
    //     c.Send(task_code);
    //     std::cout << "发送一个任务码：" << task_code << '\n';
    // }
    void Run()
    {
        int task_code = _tm.Code();
        auto &c = _cm.Select();
        std::cout << "选择一个子进程：" << c.Name() << '\n';
        c.Send(task_code);
        std::cout << "发送一个任务码：" << task_code << '\n';
    }
    void Stop()
    {
        //关闭父进程的wfd
        _cm.StopSubProcess();
        //回收所有子进程
        _cm.WaitSubProcess();
    }
    ~ProcessPool() {}

private:
    ChannelManager _cm;
    int _process_num;
    TaskManager _tm;
};

#endif